const fs = require('fs')
const proj4 = require("proj4");
const gcoord = require('gcoord');
const coords = require("epsg-index/all.json");


proj4.defs(
  "EPSG:4479",
  "+proj=geocent +ellps=GRS80 +units=m +no_defs +type=crs"
);;

const firstProjection = coords["4509"].wkt;
const secondProjection = coords["4326"].wkt;
// const secondProjection = proj4('EPSG:4479')

// console.log('secondProjection',secondProjection)

const a = fs.readFileSync('files/a.csv').toString('utf-8')
const b = fs.readFileSync('files/b.csv').toString('utf-8')

function parse(str) {
  const arr = str.split('\n').filter(Boolean)
  const head = arr.shift().split(',')
  const result =  arr.map(i => i.split(','))
  return [head, result]
}

function transform(coordinates) {
  if (coordinates.filter(Boolean).length === 3) {
    return proj4(firstProjection, secondProjection, coordinates);
  }
}

// 李佳奇,WS023313,489602.717,3544601.317,38.894,

const [aHead, aContent] = parse(a)
const [bHead, bContent] = parse(b)

const result = bContent.map(j => {
  const item = aContent.find(i => i[1] === j[0])
  if (item) {
    const coordinate = transform([
      parseFloat(item[2]),
      parseFloat(item[3]),
      parseFloat(item[4])
    ])
    
    return [
      ...j,
      item[0],
      item[1],
      ...coordinate
    ]
  }

  return [
    ...j,
    ...new Array(5).fill('')
  ]
})


const head = [...bHead, ...aHead]
const csv = [
  head,
  ...result
]
fs.writeFileSync('result.csv', csv.map(i => i.join(',').replace(/[\n\r]/, '')).join('\n'))